package com.unhz.generator.utils.service.impl;

import com.unhz.generator.utils.CommonFileAddress;
import com.unhz.generator.utils.CopyFileUtil;
import com.unhz.generator.utils.service.FileUtilService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * Created by cxg on 2017/11/10 0010.
 *
 * @Author 曹显贵
 * @Date 2017/11/10 0010 18:25
 */
@Service
public class FileUtilServiceImpl implements FileUtilService{
    //打印日志
    private Logger LOG = LoggerFactory.getLogger(FileUtilServiceImpl.class);

    @Override
    public String upload(MultipartFile file,String path){
        String fileName = file.getOriginalFilename();
        //扩展名
        String fileExtenSionName = fileName.substring(fileName.lastIndexOf(".") + 1);
        String uploadfileName = UUID.randomUUID().toString() + "." + fileExtenSionName;
        File fileDir = new File(path);
        if (!fileDir.exists()) {
            fileDir.setWritable(true);
            //创建文件
            fileDir.mkdir();
        }
        File targetFile = new File(path, uploadfileName);
        try {
            file.transferTo(targetFile);
            CopyFileUtil.copyFile(path+"/"+uploadfileName, CommonFileAddress.testCopyFilePath+uploadfileName);
            targetFile.delete();
        } catch (IOException e) {
            LOG.info("上传文件异常", e);
            return " ";
        }
        return targetFile.getName();
    }

}
